<template>
  <div class="business-management">
    <!-- 头部 -->
    <div class="header">
      <div class="header-left">
        <i class="fas fa-arrow-left" @click="goBack"></i>
        <h3>店铺管理</h3>
      </div>
      <div class="header-right">
      </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filters">
      <div class="search-box">
        <i class="fas fa-search"></i>
        <input
            type="text"
            v-model="searchKeyword"
            placeholder="搜索店铺名称"
            @input="handleSearch"
        >
      </div>
    </div>

    <!-- 店铺列表 -->
    <div class="business-list">
      <div class="table-container">
        <table class="business-table">
          <thead>
          <tr>
            <th>ID</th>
            <th>店铺名称</th>
            <th>店主</th>
            <th>地址</th>
            <th>起送价</th>
            <th>配送费</th>
            <th>状态</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="business in filteredBusinesses" :key="business.id">
            <td>{{ business.id }}</td>
            <td>
              <div class="business-info">
                <img :src="getBusinessImage(business.businessImg)" alt="店铺图片" class="business-img" @error="handleImageError">
                <span>{{ business.businessName }}</span>
              </div>
            </td>
            <td>{{ getBusinessOwnerName(business) }}</td> <!-- 修改这里 -->
            <td>{{ business.businessAddress }}</td>
            <td>¥{{ formatPrice(business.startPrice) }}</td>
            <td>¥{{ formatPrice(business.deliveryPrice) }}</td>
            <td>
        <span :class="['status', business.deleted ? 'inactive' : 'active']">
          {{ business.deleted ? '已关闭' : '营业中' }}
        </span>
            </td>
            <td>
              <div class="actions">
                <button class="btn action-btn" @click="viewBusiness(business.id)">
                  查看
                </button>
<!--                <button class="btn action-btn danger" @click="deleteBusiness(business)">-->
<!--                  删除-->
<!--                </button>-->
              </div>
            </td>
          </tr>
          </tbody>
        </table>
      </div>

      <!-- 空状态 -->
      <div class="empty-state" v-if="businesses.length === 0 && !loading">
        <i class="fas fa-store"></i>
        <p>暂无店铺数据</p>
      </div>

      <!-- 加载状态 -->
      <div class="loading" v-if="loading">
        <i class="fas fa-spinner fa-spin"></i>
        <p>加载中...</p>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { businessAPI } from '@/api/business.js'

const router = useRouter()

const businesses = ref([])
const loading = ref(false)
const searchKeyword = ref('')

// 计算属性：筛选后的店铺列表
const filteredBusinesses = computed(() => {
  if (!searchKeyword.value) {
    return businesses.value
  }

  const keyword = searchKeyword.value.toLowerCase()
  return businesses.value.filter(business =>
      business.businessName && business.businessName.toLowerCase().includes(keyword) ||
      (business.businessOwner && business.businessOwner.toLowerCase().includes(keyword)) ||
      (business.businessAddress && business.businessAddress.toLowerCase().includes(keyword))
  )
})

// 页面加载时获取店铺列表
onMounted(async () => {
  await loadBusinesses()
})

// 加载店铺列表
const loadBusinesses = async () => {
  loading.value = true
  try {
    const response = await businessAPI.getBusinesses()
    if (response.data && response.data.success === true && response.data.data) {
      businesses.value = response.data.data
    } else if (response.data) {
      businesses.value = response.data
    }
    console.log('店铺列表:', businesses.value)
  } catch (error) {
    console.error('获取店铺列表失败:', error)
    alert('获取店铺列表失败')
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 获取店铺图片
const getBusinessImage = (imagePath) => {
  if (!imagePath) {
    return require('@/assets/logo.png')
  }
  return imagePath
}

// 获取店主名称
const getBusinessOwnerName = (business) => {
  if (business.businessOwner && typeof business.businessOwner === 'object') {
    return business.businessOwner.username || '-'
  }
  return business.businessOwner || '-'
}

// 图片加载错误处理
const handleImageError = (event) => {
  event.target.src = require('@/assets/logo.png')
}

// 查看店铺详情
const viewBusiness = (businessId) => {
  router.push(`/businessInfo?id=${businessId}`)
}

// 搜索处理
const handleSearch = () => {
  // 搜索逻辑已通过计算属性实现
}

// 格式化价格
const formatPrice = (price) => {
  if (price === null || price === undefined) return '0.00'
  return parseFloat(price).toFixed(2)
}

// 删除店铺
const deleteBusiness = async (business) => {
  if (!confirm(`确定要删除店铺 "${business.businessName}" 吗？此操作不可恢复！`)) {
    return
  }

  try {
    await businessAPI.deleteBusiness(business.id)
    // 从列表中移除已删除的店铺
    businesses.value = businesses.value.filter(b => b.id !== business.id)
    alert('店铺删除成功')
  } catch (error) {
    console.error('删除店铺失败:', error)
    const errorMessage = error.response?.data?.message || '删除店铺失败'
    alert('删除失败：' + errorMessage)
  }
}
</script>

<style scoped>
.business-management {
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 20px;
  border-radius: 10px;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header-left i {
  font-size: 20px;
  color: #666;
  cursor: pointer;
}

.header-left h3 {
  margin: 0;
  color: #333;
}

.filters {
  margin-bottom: 20px;
  background: white;
  padding: 15px;
  border-radius: 10px;
}

.search-box {
  position: relative;
}

.search-box i {
  position: absolute;
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
}

.search-box input {
  width: 100%;
  padding: 10px 10px 10px 35px;
  border: 1px solid #ddd;
  border-radius: 5px;
  outline: none;
}

.business-list {
  background: white;
  border-radius: 10px;
  overflow: hidden;
}

.table-container {
  overflow-x: auto;
}

.business-table {
  width: 100%;
  border-collapse: collapse;
}

.business-table th,
.business-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

.business-table th {
  background: #f8f9fa;
  font-weight: 600;
  color: #333;
}

.business-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.business-img {
  width: 40px;
  height: 40px;
  border-radius: 5px;
  object-fit: cover;
}

.status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.status.active {
  background: #d4edda;
  color: #155724;
}

.status.inactive {
  background: #f8d7da;
  color: #721c24;
}

.actions {
  display: flex;
  gap: 5px;
}

.btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.action-btn {
  background: #6c757d;
  color: white;
}

.action-btn.danger {
  background: #dc3545;
  color: white;
}

.empty-state,
.loading {
  text-align: center;
  padding: 40px;
  color: #999;
}

.empty-state i,
.loading i {
  font-size: 48px;
  margin-bottom: 10px;
}

@media (max-width: 768px) {
  .header {
    flex-direction: column;
    gap: 15px;
  }

  .business-info {
    flex-direction: column;
    align-items: flex-start;
  }

  .actions {
    flex-direction: column;
  }
}
</style>